﻿#include "zmq.h"
#include "zmqrequester.h"
#include "WaitUtils.h"
#include "widgettcpcfg.h"

#define CHAR_MAX_LENGTH        1024

ZmqRequester::ZmqRequester(QObject *parent):BaseRequester(parent)
{

}

ZmqRequester::~ZmqRequester()
{

}

bool ZmqRequester::connectToHost()
{
    _context=zmq_ctx_new();
    _socket=zmq_socket(_context,ZMQ_REQ);
    QString ip=_obj["address"].toString();
    int rc=zmq_connect(_socket,  ip.toUtf8().data());
    qDebug()<<__FUNCTION__<<__LINE__<<ip<<rc;
    if(rc!=0)
    {
        return false;
    }

    int timeout=3000;
    zmq_setsockopt(_socket, ZMQ_SNDTIMEO, &timeout, sizeof(timeout)); // 设置发送超时
    if(zmq_setsockopt(_socket, ZMQ_RCVTIMEO, &timeout, sizeof(int)) < 0)
    {
        qDebug()<<"Failed to setsocketopt ZMQ_RCVTIMEO error";
    }
    return true;
}

bool ZmqRequester::isConnected()
{
    return true;
}

bool ZmqRequester::disConnect()
{
    zmq_close(_socket);
    zmq_ctx_destroy(_context);
    return true;
}

QByteArray ZmqRequester::request(QByteArray data)
{
    char *receivetMsg=new char[CHAR_MAX_LENGTH*10];
    for (int i = 0; i < 3; ++i)
    {
        int sendLen = zmq_send(_socket, data.data(), data.length(), 0);
        if (sendLen >= 0)
        {
            // 等待一段时间，这里可以根据具体情况调整
            WaitUtils::WaitMsNoException(50);

            // 接收数据时获取实际接收的长度
            int recvLen = zmq_recv(_socket, receivetMsg, sizeof(receivetMsg) - 1, 0);
            if (recvLen >= 0)
            {
                const QByteArray& arr=QByteArray::fromRawData(receivetMsg,recvLen);
                delete[] receivetMsg;
                return arr;
            }
        }
    }
    delete[] receivetMsg;
    return QString("send error!").toUtf8();
}

bool ZmqRequester::requestNoReply(QByteArray data)
{
    return true;
}

QWidget *ZmqRequester::getConfigWidget()
{
    WidgetTcpCfg *cfg=new WidgetTcpCfg();
    cfg->setComm(this);
    return cfg;
}
